package cn.gxa.edu_adm.filter;

import cn.gxa.edu_adm.bean.Admin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问  login有关请求 直接通过
 * 无关的被过滤   如果有登录那么进入想进入url 如果判断没有登录信息那么久跳到login.html
 */
@WebFilter(filterName = "IsLoginFilter", urlPatterns = {"/aaa"})
public class IsLoginFilter implements Filter {
    public IsLoginFilter() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //向下转型
        HttpServletRequest request = (HttpServletRequest)req;
        //获取前端想 请求地址
        String url = request.getRequestURI();
        //判断请求地址中是否包含  login
        if (url.toLowerCase().contains("login")||
                //静态资源 css   js  layui  image 放行
                url.contains("/css/") || url.contains("/js/") ||
                url.contains("/layui/") || url.contains("/image/")) {
            //login.html  或者  checkLogin
            chain.doFilter(req, resp);
        } else {
            //从session中获取 admin  是否存在
            Admin admin = (Admin)request.getSession().getAttribute("admin");
            if (admin == null) {
                //跳转到登录
                ((HttpServletResponse)resp).sendRedirect("login.html");
            } else {
                //进入 url
                chain.doFilter(req, resp);
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
